package com.wenhuitec.android.tang.ui.activity;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemProperties;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.alipay.iot.bpaas.api.BPaaSApi;
import com.alipay.iot.bpaas.api.BPaaSInitCallback;
import com.alipay.iot.bpaas.api.InnerApi;
import com.alipay.iot.bpaas.api.ipc.IpcChannel;
import com.alipay.iot.bpaas.api.ipc.IpcListener;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.InitFinishCallback;
import com.dhkj.printlib.PrintStart;
import com.dhkj.web.basic.Constans;
import com.dhkj.web.systemcenter.SysCenterRequestUtils;
import com.dhkj.web.utils.MyObserverRes;
import com.lake.banner.uitls.SystemUtils;
import com.wenhuitec.android.tang.R;

import java.lang.reflect.Method;
import java.math.BigDecimal;

import androidx.annotation.NonNull;

public class BottomTabActivity extends TabActivity1 implements View.OnClickListener {

    private static final String TAG = "BottomTabActivity";

    /**
     * 显示的三个Activity的class
     */
    private Class<?> activities[] = {Activity1.class, Activity2.class, ReportActivity.class, Activity4.class};

    /**
     * i
     * 菜单的三个button
     */
    private RelativeLayout[] btn = new RelativeLayout[4];

    /**
     * 当前的选择
     */
    private int currentSelect;

    private String templateId = "2021004104615091";

    private String abcpApplicationAppId = "2021004101630874";

    private String templateServiceCode = "BPaaSTemplateChannel";

    private TextView btn_1_text;
    private TextView btn_2_text;
    private TextView btn_3_text;
    private ImageView btn_1;
    private ImageView btn_2;
    private ImageView btn_3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab);
        setContainer(R.id.fl_container);
//        PrintStart.with(this);
        String model = SystemProperties.get("ro.product.model");
        SharedPreferences sysInfo = getSharedPreferences("sysCost", MODE_PRIVATE);
        String sysApi = sysInfo.getString("api", null);
        int type = sysInfo.getInt("type", 0);
        if (sysApi == null) {
            //跳转新页面设置
            BindActivity.startAct(this);
            finish();
            return;
        } else {
            Constans.getInstance().BaseUrl = sysApi;
//            ConfigConstant.BASE_API_URL = sysApi;
//            ConfigConstant.abcpAppId = abcpAppid;
//            ConfigConstant.abcpAppVersion = abcpAppVersion;
//            ConfigConstant.logicGroupID = logicGroupId;
//            ConfigConstant.devPSK = devPsk;
        }
        init();

        SysCenterRequestUtils.init(this, SystemUtils.getSerialNumber(), new MyObserverRes<JSONObject>(this, false) {
            @Override
            public void onSuccess(JSONObject result) {
                System.out.println("请求成功：" + result.toJSONString());
                JSONObject shopMachineJson = result.getJSONObject("shopMachine");
                JSONObject deviceJson = result.getJSONObject("device");

                if (shopMachineJson == null || shopMachineJson.isEmpty()) {

                } else {
                    SharedPreferences userInfo = getSharedPreferences("sysCost", MODE_PRIVATE);
                    SharedPreferences.Editor editor = userInfo.edit();
                    editor.putString("api", shopMachineJson.getString("businessUrl"));
                    editor.putInt("type", new BigDecimal(deviceJson.getString("type")).intValue());
                    editor.putString("merchantName", shopMachineJson.getString("merchantName"));
                    editor.commit();

                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                System.out.println("请求失败");
            }
        });


        if (type == 1) {
            activities[1] = ActivityCK.class;
            activities[2] = ActivityCheckOrder.class;
        }

//        System.out.println(getSN());
//        btn_trans =(ImageView)findViewById(R.id.btn_1);
//        btn_yizu =(ImageView)findViewById(R.id.btn_2);
//        btn_mine =(ImageView)findViewById(R.id.btn_3);
//        btn_trans_text = (TextView)findViewById(R.id.btn_1_text);
//        btn_yizu_text = (TextView)findViewById(R.id.btn_2_text);
//        btn_mine_text = (TextView)findViewById(R.id.btn_3_text);
        btn[0] = (RelativeLayout) findViewById(R.id.bottom_bar_1_btn);
        btn[0].setOnClickListener(this);
        btn[1] = (RelativeLayout) findViewById(R.id.bottom_bar_2_btn);
        btn[1].setOnClickListener(this);
        btn[2] = (RelativeLayout) findViewById(R.id.bottom_bar_3_btn);
        btn[2].setOnClickListener(this);
        btn[3] = (RelativeLayout) findViewById(R.id.bottom_bar_4_btn);
        btn[3].setOnClickListener(this);
        showActivity(activities[0]);
//        btn_trans.setImageResource(R.drawable.icon_trans2);
//        btn_trans_text.setTextColor(Color.parseColor("#2E59F9"));
    }

    public static String getSN() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            String serial = null;
            try {
                Class<?> c = Class.forName("android.os.SystemProperties");
                Method get = c.getMethod("get", String.class);
                serial = (String) get.invoke(c, "ro.sunmi.serial");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return serial;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return Build.getSerial();
        } else {
            return Build.SERIAL;
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.bottom_bar_1_btn:
//                btn_trans.setImageResource(R.drawable.icon_trans2);
//                btn_trans_text.setTextColor(Color.parseColor("#2E59F9"));
//
//                btn_yizu.setImageResource(R.drawable.icon_minzu1);
//                btn_yizu_text.setTextColor(Color.parseColor("#48000000"));
//
//                btn_mine.setImageResource(R.drawable.icon_me1);
//                btn_mine_text.setTextColor(Color.parseColor("#48000000"));
                currentSelect = 0;
                showActivity(activities[0]);
                break;
            case R.id.bottom_bar_2_btn:
//                btn_trans.setImageResource(R.drawable.icon_trans1);
//                btn_trans_text.setTextColor(Color.parseColor("#48000000"));
//                btn_yizu.setImageResource(R.drawable.icon_minzu2);
//                btn_yizu_text.setTextColor(Color.parseColor("#2E59F9"));
//                btn_mine.setImageResource(R.drawable.icon_me1);
//                btn_mine_text.setTextColor(Color.parseColor("#48000000"));
                currentSelect = 1;
                showActivity(activities[1]);
                break;
            case R.id.bottom_bar_3_btn:
//                btn_trans.setImageResource(R.drawable.icon1);
//                btn_trans_text.setTextColor(Color.parseColor("#48000000"));
//                btn_yizu.setImageResource(R.drawable.icon2);
//                btn_yizu_text.setTextColor(Color.parseColor("#48000000"));
//                btn_mine.setImageResource(R.drawable.icon3);
//                btn_mine_text.setTextColor(Color.parseColor("#2E59F9"));
                currentSelect = 2;
                showActivity(activities[2]);
                break;
            case R.id.bottom_bar_4_btn:
//                btn_trans.setImageResource(R.drawable.icon1);
//                btn_trans_text.setTextColor(Color.parseColor("#48000000"));
//                btn_yizu.setImageResource(R.drawable.icon2);
//                btn_yizu_text.setTextColor(Color.parseColor("#48000000"));
//                btn_mine.setImageResource(R.drawable.icon3);
//                btn_mine_text.setTextColor(Color.parseColor("#2E59F9"));
                currentSelect = 3;
                showActivity(activities[3]);
                break;
        }
    }

    private void init() {
        Log.i(TAG, "init");
        try {
            // 如果iot初始化成功
            if (APIManager.getInstance().getDeviceAPI().getDeviceSn() != null) {
                initABCP();
                return;
            }
            //iot sdk初始化成功后，再初始化SDK
            APIManager.getInstance().initialize(getApplicationContext(), abcpApplicationAppId, success -> {
                Log.d(TAG, "iot sdk init success = " + success);
                if (success) {
                    initABCP();
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "APIManager initialize error", e);
        }
    }


    /**
     * bpaas api初始化  传入在BPaas平台上申请到的Appid、应用版本号信息
     */
    public void initABCP() {
        //模板应用appid_c1
        Bundle extInfo = new Bundle();
        extInfo.putString("ext_tpl_app_id", templateId);
        extInfo.putInt("ext_tpl_display_mode", 1);
        extInfo.putBoolean("isFloat", true);
        //bpaas api初始化  传入在BPaas平台上申请到的Appid、应用版本号信息
        BPaaSApi.getInstance().init(getApplicationContext(), abcpApplicationAppId, extInfo, new BPaaSInitCallback() {
            @Override
            public void onSuccess() {
                Log.i(TAG, "init ABCP success");
                clickInit(null);
                InnerApi.addIpcListener(mIpcListener);
            }

            @Override
            public void onFail(String msg) {
                Log.e(TAG, "init ABCP fail reason:" + msg);
            }
        });
    }

    private IpcListener mIpcListener = new IpcListener() {
        @Override
        public void onConnected(IpcChannel ipcChannel) {
            Log.i(TAG, "onConnected");
            init();
        }

        @Override
        public void onDisconnected(IpcChannel ipcChannel) {
            Log.i(TAG, "onDisconnected");
        }

        @Override
        public void onConnectionFailed(IpcChannel ipcChannel) {
            Log.i(TAG, "onConnectionFailed");
        }
    };

    // 团餐模板初始化
    public void clickInit(View view) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("logicGroupID", "BUSINESS_2291311712665600");
        jsonObject.put("industryBizType", "business");
        jsonObject.put("partnerId", "2088121760636121");
        jsonObject.put("merchantId", "2088441828867338");
        jsonObject.put("merchantName", "广州市鼎鸿电子科技有限公司");
        jsonObject.put("isvName", "广州市鼎鸿电子科技有限公司");
        jsonObject.put("useOfflinePay", true);
        jsonObject.put("uploadTimeOutSecs", 15); // 等待结果页支付查询超时时间，默认30s


        Bundle bundle = new Bundle();
        bundle.putString("templateId", templateId);
        bundle.putString("operateType", "init");
        bundle.putString("page", "canteen");
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(abcpApplicationAppId, templateServiceCode, bundle, new BPaaSCallback() {
            @Override
            public void onResponse(BPaaSResponse response) {
//                        responseInvoke(response, "canteen init");
            }

            @Override
            public void onEvent(String eventId, String data, Bundle extra) {
                Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
            }
        });
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //页面退出时移除IpcListener，避免内存泄露
        InnerApi.removeIpcListener(mIpcListener);
    }
}
